package com.security.demo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.security.demo.entity.User;
import com.security.demo.mapper.UserMapper;
import com.security.demo.service.UserService;
import com.security.demo.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 重写UserDetailsService的loadUserByUsername方法
     * 用于登录验证和角色授权
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.getUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名为null");
        }
        // 这里需要将User转换为UserDetails，并设置角色的GrantedAuthority集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole()));
        // 如果是admin角色，就多添加USER权限
        if(user.getRole().equals("ADMIN")){
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(user.getPassword());
        return new org.springframework.security.core.userdetails.User(user.getName(), password, authorities);
    }



    /**
     *  分页条件查询用户名
     */
    @Override
    public R getUserList(String name, int current, int size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Page<User> page = new Page<>(current, size);
        if(name!=null && !name.isEmpty()){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");  // 指定根据id倒序
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return R.ok().data("userPage", userPage);
    }

    /**
     * 新增用户
     */
    @Override
    public R addUser(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getName());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null) {
            return R.error().setMessage("该用户名已存在");
        }
        userMapper.insert(user);
        return R.ok().setMessage("新增成功！");
    }

    /**
     * 更新用户
     */
    @Override
    public R updateUser(User user) {
        // 根据用户名查询是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getName());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null && user1.getId() != user.getId()) {
            return R.error().setMessage("该用户名已存在");
        }
        // 不重复就根据id来修改用户信息
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", user.getId());
        userMapper.update(user, queryWrapper1);
        return R.ok().setMessage("更新成功！");
    }

    /**
     * 删除用户
     */
    @Override
    public R deleteUser(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return R.error().setMessage("没有该用户");
        }
        userMapper.deleteById(user.getId());
        return R.ok().setMessage("删除成功");
    }

    /**
     * 根据用户名查询用户信息
     */
    @Override
    public User getUserByName(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return userMapper.selectOne(queryWrapper);
    }

}
